<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'messageReplies:blog_message_replies:deleteBatch'"
            >批量操作
            <Icon icon="mdi:chevron-down" />
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell> </template>
    </BasicTable>
    <!-- 表单区域 -->
    <BlogMessageRepliesModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="messageReplies-blogMessageReplies" setup>
  import { reactive } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import BlogMessageRepliesModal from './components/BlogMessageRepliesModal.vue';
  import { columns, searchFormSchema, superQuerySchema } from './BlogMessageReplies.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, reviewMessageReply } from './BlogMessageReplies.api';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const queryParam = reactive<any>({});
  //注册model
  const [registerModal, { openModal }] = useModal();
  //注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      title: 'blog_message_replies',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: 'blog_message_replies',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 发布留言回复
   */
  async function handlePublish(record: Recordable) {
    try {
      console.log('发布留言回复，原始数据:', record);
      const updateData = { ...record, status: 1 };
      console.log('发布留言回复，更新数据:', updateData);
      await reviewMessageReply(updateData);
      createMessage.success('发布成功');
      handleSuccess();
    } catch (error) {
      console.error('发布失败:', error);
      createMessage.error('发布失败');
    }
  }
  /**
   * 拒绝留言回复
   */
  async function handleReject(record: Recordable) {
    try {
      console.log('拒绝留言回复，原始数据:', record);
      const updateData = { ...record, status: 2 };
      console.log('拒绝留言回复，更新数据:', updateData);
      await reviewMessageReply(updateData);
      createMessage.success('拒绝成功');
      handleSuccess();
    } catch (error) {
      console.error('拒绝失败:', error);
      createMessage.error('拒绝失败');
    }
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    const actions: any[] = [];

    // 编辑按钮始终显示
    actions.push({
      label: '编辑',
      onClick: handleEdit.bind(null, record),
      auth: 'messageReplies:blog_message_replies:edit',
    });

    // 根据状态显示不同按钮
    if (record.status === 0) {
      // 待审核状态：显示审核按钮
      actions.push({
        label: '审核',
        popConfirm: {
          title: '请选择审核结果',
          okText: '发布',
          cancelText: '拒绝',
          confirm: handlePublish.bind(null, record),
          cancel: handleReject.bind(null, record),
          placement: 'topLeft',
        },
      });
    } else {
      // 其他状态：显示删除按钮
      actions.push({
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        auth: 'messageReplies:blog_message_replies:delete',
      });
    }

    return actions;
  }
  /**
   * 下拉操作栏
   */
  function getDropDownAction(_record) {
    return [];
  }
</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>
